import cv2
import os
from datetime import datetime, timedelta

def extract_frames(video_path, output_folder):
    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)


    print(cv2.getBuildInformation())
    
    # 获取视频的FPS
    fps = cap.get(cv2.CAP_PROP_FPS)
    
    # 获取视频开始时间（使用当前时间作为基准）
    start_time = datetime.now()
    
    frame_count = 0
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
            
        # 计算当前帧的时间戳
        timestamp = start_time + timedelta(seconds=frame_count/fps)
        frame_time = timestamp.strftime('%H-%M-%S-%f')[:-3]  # 精确到毫秒
        
        # 保存帧
        output_path = os.path.join(output_folder, f'frame_{frame_count:06d}_{frame_time}.jpg')
        cv2.imwrite(output_path, frame)
         
        frame_count += 1
        print(f"第 {frame_count} 帧")
    
    cap.release()
    print(f'总共提取了 {frame_count} 帧')
    
    # 计算一秒钟有多少帧
    print(f'一秒钟有 {fps} 帧')
    
if __name__ == '__main__':
    video_path = r'D:\tennis\videos\line_videos\done\1734661378089.h264'
    output_folder = r'D:\home\code\videos_project\images_tmp'
    # 删除目录下的文件
    if os.path.exists(output_folder):
        for file in os.listdir(output_folder):
            os.remove(os.path.join(output_folder, file))

    
    extract_frames(video_path, output_folder)



# frame_000000_14-38-06-036
# frame_002872_14-38-17-524


# 2750 + 495/(1000/250) = 2750 + 123.75 = 2873.75
# 14-38-17-524



# frame_000320_15-26-49-213

#frame_000332_15-26-49-261

# 17/(1000/250) = 4.25
